package cn.yx.common.jpa.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.yx.common.jpa.properties.SnowflakeProperties;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * <p>雪花算法服务类，为Hibernate获取基于雪花算法的ID</p>
 *
 * @author Wgssmart
 */
@Component
public class SnowflakeService implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private final SnowflakeProperties snowflakeProperties;

    public SnowflakeService(SnowflakeProperties snowflakeProperties) {
        this.snowflakeProperties = snowflakeProperties;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SnowflakeService.applicationContext = applicationContext;
    }

    public static SnowflakeService getService() {
        return applicationContext.getBean(SnowflakeService.class);
    }

    /**
     * 获取雪花算法ID
     *
     * @return
     */
    public long nextId() {
        Snowflake snowflake = IdUtil.getSnowflake(snowflakeProperties.getWorkerId(), snowflakeProperties.getDataCenterId());
        return snowflake.nextId();
    }
}
